# -*- coding: utf-8 -*-
import json
import logging
from traceback import format_exc

import pymongo

from zc_core.client.mongo_client import Mongo
from ctaxccgp.simple.order_crawler import OrderCrawler
from ctaxccgp.simple.redis_util import RedisUtil


class Consumer(object):
    def __init__(self, batch_no, *args, **kwargs):
        self.batch_no = batch_no
        self.redis_util = RedisUtil(batch_no)

    def init_batch(self):
        try:
            if not self.redis_util.exists_batch():
                # pool_list = Mongo().list('sku_pool', query={'offlineTime': {'$lte': 2}}, fields={'_id': 1, 'supplierId': 1})
                pool_list = Mongo().list('data_20201109', fields={'_id': 1, 'supplierId': 1}, sort=[("soldCount", pymongo.DESCENDING)])
                rows = [json.dumps(row) for row in pool_list]
                self.redis_util.init_tasks(rows)
                logging.info('任务数量: %s' % len(pool_list))
            else:
                logging.info('批次存在: %s' % self.batch_no)
        except Exception as e:
            logging.info(format_exc())
            _ = e

    def run(self):
        try:
            while True:
                task = self.redis_util.get_task()
                if task:
                    sku = json.loads(task)
                    order_crawler = OrderCrawler(sku)
                    order_crawler.run()
                else:
                    break
        except Exception as e:
            logging.info(format_exc())
            _ = e


if __name__ == '__main__':
    consumer = Consumer(20201111)
    consumer.init_batch()
    consumer.run()
